/* 
 * fix for new edits which cant be edited,deleted,viewed
 */

var schedules = {
    
    request:$("#req_id").val(),

    init:function() {
        $("#update_form input.location").autocomplete({
            source: $("#iata-auto-complete-source").val(), // specified in URLs element
            minLength: 2
        });
        
        $("#update_form #handler_id").chosen();
    },
    
    delForm:function(gid){

        var url_req = $("#del_service").val();
        var query = "req_id="+gid;

        $.ajax({
            url:url_req,
            data: query,
            dataType: 'json',
            type: 'POST',
            success: function(data) {
                alert("Data Deleted");
            }
        });

    }
};


var Services = {
    
    liveBinded: false,
    
    init: function() {
        Services.bindScheduleElements();
        Services.bindAttachmentElements();
        Services.bindLiveServiceElements();
    },
    
    bindScheduleElements: function() {
        if( $("#ground_request_schedule_id").val() == "" ) {
            $("#services_section").hide();
        }
        
        $("#dates_section input.date").datetimepicker({
            dateFormat: 'yy-mm-dd',
            timeFormat: 'hh:mm:ss',
            changeMonth: true,
            changeYear: true
        });
        
        $("#dates_section input.location").autocomplete({
            source: $("#iata-auto-complete-source").val(), // specified in URLs element
            minLength: 2
        });
        
        $("#services_add_new").data({
            "load-callback": Services.bindServiceDialogElements,
            callback: Services.updateList,
            height: 575,
            width: 800
        });
        
        $("select#handler_id").change(function() {
            
            $("#schedule_save_status").show();
            
            var url = $(this).parents("form").attr('action');
            var query = $(this).parents("form").serialize();
            
            $.ajax({
                url: url,
                data: query,
                dataType: 'json',
                type: 'post',
                success: function(data) {
                    
                    $("#ground_request_schedule_id").val( data.ground_request_schedule_id );
                    $("#services_add_new").attr("href", $("#services_add_new").attr("href") + "/" + data.ground_request_schedule_id);
                    
                    $("#attachments_add_new").attr("href", $("#attachments_add_new").attr("href") + "/" + data.ground_request_schedule_id);
                    $("#attachment_list").attr("data-url", $("#attachment_list").attr("data-url") + "/" + data.ground_request_schedule_id);
                    
                    $("#schedule_save_status, #handler_select_notice").hide();
                    $("#services_section").show('slow');
                },
                error: function(xhr) {
                    $("#schedule_save_status").hide();
                    console.log(xhr.responseText);
                }
            });
        }).chosen();
        
        if( $("select#handler_id").val() != "" ) {
            $("#handler_select_notice").hide();
        }
    },

    bindServiceDialogElements: function() {
        $("#service_form_wrapper select").chosen();
        
        $("#service_form_wrapper #services").change(function() {
            Services.loadServiceEditor( $(this).data('href'), $(this).val() );
        });
    },
    
    bindLiveServiceElements: function() {
        if( !Services.liveBinded ) {
            $("#schedule_service_list tbody .edit_link").live('click', function(e) {
                e.preventDefault();
                
                var url = $("#services_edit_url").val();
                var query = {
                    schedule_service_id: $(this).data('id')
                };
                
                $.post(url, query, function(data) {
                    core.showDialog({
                        title: 'Edit Service Details',
                        content: data,
                        height: 575,
                        width: 800,
                        load: Services.bindServiceDialogElements//,
                    //close: Services.updateList
                    }); 
                });
            });

            $("#schedule_service_list tbody .del_service_link").live('click', function(e) {
                e.preventDefault();
                
                if( !confirm('Are you sure you want to delete this requested service')) {
                    return;
                }

                var self = this;
                var url = $("#services_delete_url").val();
                var query = {
                    schedule_service_id: $(this).data('id')
                };

                $.post(url, query, function(data) {
                    $(self).parents('tr').remove();
                    Services.updateList();
                });
            });  
            
            Services.liveBinded = true;
        }
    },
    
    bindAttachmentElements: function() {
        
        $("#attachments_add_new").data({
            'load-callback': function() {
                Services.Attachments.init();
            }
        });
        
        Services.Attachments.bindListItems();
    },
    
    loadServiceEditor: function(url, service_id) {
        var query = {
            "service_id": service_id
        };
        
        $.ajax({
            url: url,
            data: query,
            //dataType: 'json',
            type: 'post',
            success: function(data) {
                $("#service_form_wrapper section").html(data);
                
                $("#service_form_wrapper section select").chosen();
            },
            error: function(xhr) {
                console.log(xhr.responseText);
            }
        });
    },
    
    updateList: function(data) {
        if( data != null ) {
            console.log(data);
            $("#schedule_service_list tbody").append(
                $("<tr />")
                .append( 
                    $("<td />").addClass('count').attr({
                        align: 'right', 
                        width: '20'
                    }).html("1.") 
                    )
                .append( $("<td />").html( data.Service.name ) )
                .append( $("<td />").html( data.GroundRequestScheduleService.name) )
                .append( $("<td />").html( data.GroundRequestScheduleService.contact_number) )
                .append( $("<td />").attr('align','center').html(
                    "<a class='edit_link' data-id='" + data.GroundRequestScheduleService.id + "' href='#'>Edit</a>" + 
                    "<a class='delete_link' data-id='" + data.GroundRequestScheduleService.id + "' href='#'>Delete</a>"
                    ))
                );
        }
        
        
        var count = 1;
        $("#schedule_service_list tbody .count").each(function() {
            $(this).html(count++ + ".");
        });
    },
    
    
    Attachments: {
        
        // a boolean to track selection so FF does not close dialog
        filesSelected: false,
        
        init: function() {
            
            var self = this;
                self.filesSelected = false;
            
            $("#attachments_fs").change(function(evt) {
                if( evt.target.files != null ) {
                    
                    var total_size = 0;
                    
                    var $ul = $("<ol />").css('list-style-type', 'decimal');
                    $.each(evt.target.files, function(k,v) {
                        var size = (v.size / 1024).toFixed(2) + " KB";
                        total_size += v.size;
                            
                        if( parseFloat(size) > 1024 ) {
                            size = (parseFloat(size) / 1024).toFixed(2) + " MB";
                        }
                            
                        $ul.append( $("<li />").html(v.name + " (" + size + ")") );
                    });
                    
                    var max_size_raw = $("#max_size_value").html();
                    var max_size_value = parseInt(max_size_raw.replace("M", ""));
                    
                    if( total_size > (max_size_value * 1024 * 1024) ) {
                        $("#file_list").html("").append("<span style='color: #900; font-weight: bold;'>Error! Max Upload Size of " + max_size_raw + " Exceeded</span>");
                        $("#up_save_btn").attr('disabled','');
                    }
                    
                    else {
                        $("#file_list").html("<b>Files To Upload</b> <br /><br />").append( $ul ); 
                        $("#up_save_btn").removeAttr('disabled');
                    }
                }
                
                // IE and other boys
                else {
                    $("#up_save_btn").removeAttr('disabled');
                }
                
                self.filesSelected = true;
            });
            
            $("#upload-frame").load(function(e) {
                if( self.filesSelected ) {
                    core.closeDialog();
                    Services.Attachments.updateAttachmentList();
                }
            });
            
            $("#up_save_btn").click(function() {
                $("#upload_status").html("Attaching Documents To Flight Schedule...");
                $("#AttachmentAddForm").unbind("submit").submit();
            });
            
        },
        
        bindListItems: function() {
            $("#attachment_list .delete_link").click(function(e) {
                e.preventDefault();
                 
                if( !confirm('Are you sure you want to delete this attachment?') ) {
                    return;
                } 
                
                var $this = $(this);
            
                $.get( $this.attr('href'), function(data) {
                    $this.closest("tr").remove();
                });
            });
        },
        
        updateAttachmentList: function() {
            var url = $("#attachment_list").data('url');
            
            $.get(url, function(data) {
                $("#attachment_list").html(data);
                Services.Attachments.bindListItems();
            });
        }
    }
};

$(document).ready(function(){
    schedules.init();
});